package com.example.app.gateway.filter;

import com.example.app.gateway.config.AuthProperties;
import com.example.common.result.Result;
import com.example.common.utils.JWTUTils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import com.alibaba.fastjson.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.List;
@RequiredArgsConstructor
@Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
   @Autowired
    private AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        log.info("{}进入",request.getPath());
        //判读是否拦截之外的路径
        if (isExclude(request.getPath().toString())){
            log.info("{}放行",request.getPath());
            return chain.filter(exchange);
        }
        //获取token
        String token = null;
        List<String> headers = request.getHeaders().get("token");
        if (headers!=null && !headers.isEmpty()){
             token = headers.get(0);
        }else {
            log.info("{}token为空", request);
            // 调用返回JSON格式的错误响应方法
            return unauthorizedResponse(exchange.getResponse(), "NOT_LOGIN");
        }
        String username = null;
        try{
            Claims claims = JWTUTils.parseToken(token);
            username = (String) claims.get("username");
        }catch (ExpiredJwtException e){
            log.info("{}token有误", request);
            return unauthorizedResponse(exchange.getResponse(), "TOKEN_INVALID");
        }
        //传递管理
        String UserInfo =username;
        ServerWebExchange swe = exchange.mutate().request(builder -> builder
                .header("user-info", UserInfo))
                .build();

        return chain.filter(swe);
    }


    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        if (excludePaths==null){
            return false;
        }
        for (String pathPattern: authProperties.getExcludePaths()){
            if (antPathMatcher.match(pathPattern,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return -1;
    }

    // 修改的部分：返回JSON格式的错误响应
    private Mono<Void> unauthorizedResponse(ServerHttpResponse response, String message) {
        response.setStatusCode(HttpStatus.OK); // 将状态码设置为200 OK
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Result error1 = Result.error(message);
        // 使用JSONObject创建错误消息
        String error = JSONObject.toJSONString(error1);
        DataBufferFactory bufferFactory = response.bufferFactory();
        DataBuffer buffer = bufferFactory.wrap(error.getBytes(StandardCharsets.UTF_8));

        return response.writeWith(Mono.just(buffer));
    }
}
